import axios, { AxiosRequestConfig } from 'axios'
import { App } from 'vue'

const instance = axios.create({ timeout: 30000, withCredentials: true })

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response.data.data
  },
  function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error)
  }
)

interface CustomAxiosRequestConfig<D = any> extends AxiosRequestConfig<D> {
  // 是否返回原始ajax响应结果. 只有为true时才返回原始响应
  returnOriginalResp: boolean
}

export function get<T>(
  url: string,
  params: Record<string, unknown>
): Promise<T> {
  return instance.get(url, { params: params })
}
export function post<T>(
  url: string,
  data: Record<string, unknown>,
  params?: Record<string, unknown>
): Promise<T> {
  return instance.post(url, { data, params })
}
export function del<T>(
  url: string,
  params: Record<string, unknown>
): Promise<T> {
  return instance.delete(url, { params: params })
}
export interface AjaxUtilType {
  get: <T>(url: string, params: Record<string, unknown>) => Promise<T>
  post: <T>(
    url: string,
    data: Record<string, unknown>,
    params?: Record<string, unknown> | undefined
  ) => Promise<T>
  del: <T>(url: string, params: Record<string, unknown>) => Promise<T>
}
export const AjaxUtil: AjaxUtilType = { get, post, del }

export function installGlobal(app: App) {
  app.config.globalProperties.$ajax = { get, post, del }
}
export default instance
